package jmu.controller;

import jakarta.servlet.http.HttpSession;
import jmu.service.StudentsService;
import jmu.vo.Students;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/students")
public class StudentsController {
    @Autowired
    private StudentsService studentsService;

    @RequestMapping("/findAll")
    public String findAllStudents(Model model) throws Exception {
        List<Students> all = this.studentsService.findAllStudents();;
        System.out.println("controll-all元素个数:"+all.size());
        model.addAttribute("allStudents",all);
        return "students/showStudents";
    }

    // 显示登录页面（GET请求）
    @GetMapping("/login")
    public String showLoginForm() {
        return "students/login";
    }

    // 处理登录请求（POST请求）
    @PostMapping("/login")
    public String handleLogin(
            @RequestParam("studentId") String studentId,
            @RequestParam("password") String password,
            HttpSession session) {

        Students student = studentsService.isValidUser(studentId, password);
        if (student != null) {
            session.setAttribute("currentUser", student); // 将用户对象存入 Session
            return "redirect:/messages/list";
        } else {
            // 登录失败处理
            return "redirect:/students/login?error";
        }
    }
}
